const bcrypt = require('bcryptjs');
const {sequelize} = require('../../core/db')
const {Sequelize, Model} = require('sequelize');

class User extends Model {
    static async verifyEmailPassword(email, plainPassword) {
        const user = await User.findOne({
            where: {
                email
            }
        });
        if(!user) {
            throw new global.errs.NotFound('账号不存在!');
        }
        const correct = bcrypt.compareSync(plainPassword, user.password);
        if(!correct) {
            throw new global.errs.AuthFailed('授权失败');
        }
        return user
    }
    
    // // 验证用户openid是否正确
    static async getUserByOpenid(openid) {
       const user = await User.findOne({
           where: {
               openid
           }
       });
       return user;
    }

    // // 验证成功之后添加数据
    static async registerByOpenid(openid) {
        return await User.create({
            openid
        })
    }
}
        
User.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    nickname: Sequelize.STRING,
    email: {
        type: Sequelize.STRING,
        unique: true 
    },
    password: {
        type: Sequelize.STRING,
        set(val) {
            const salt = bcrypt.genSaltSync(10);
            const pws = bcrypt.hashSync(val, salt);
            this.setDataValue('password', pws)
        }
    },
    openid: {
        type: Sequelize.STRING,
        unique: true
    }
},{
    sequelize,
    tableName: 'user'
});

module.exports = User
